
import request from '../../utils/request';

Page({
  data: {
    arr22: [],
    selectTyae: 0,
    imgArr: [],
    pagePairs: [],
    index: ''
  },

  onLoad() {
    this.loadBooks()
  },

  // 获取书列表
  async loadBooks() {
    const res = await request({
      url: 'http://192.168.1.54:8005/sample-books',
      method: 'GET'
    })
    const list = res.data.list
    this.setData({
      arr22: list,
      index: list[0].id
    })
    this.loadImages()
  },

  // 加载图片
  async loadImages() {
    const res = await request({
      url: `http://192.168.1.54:8005/sample-books/${this.data.index}`,
      method: 'get'
    })
    const images = res.data.images || []

    // 组合成前后页对
    const pairs = []
    for (let i = 0; i < images.length; i += 2) {
      pairs.push({
        front: images[i],
        back: images[i + 1] || null,
        turned: false,
        zIndex: 1
      })
    }

    this.setData({
      imgArr: images,
      pagePairs: pairs
    })
  },

  // 点击翻页
  flipPage(e) {
    const index = e.currentTarget.dataset.index
    const updated = this.data.pagePairs.map((item, i) => {
      return {
        ...item,
        turned: i === index ? !item.turned : item.turned,
        zIndex: i === index ? 3 : 1
      }
    })
    this.setData({
      pagePairs: updated
    })
  },

  // 点击切换书
  tiaozdf(e) {
    const index = e.currentTarget.dataset.index
    const item = this.data.arr22[index]
    this.setData({
      selectTyae: index,
      index: item.id
    })
    this.loadImages()
  }
})
